package jtt809.handler;

import com.sjx.jtt809.pojo.Response;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import jtt809.business.ClientBusinessFactory;

/**
 * 从链路处理器
 */
public class SlaveLinkClientJtt809Handler extends SimpleChannelInboundHandler<Response> {

    public static final Log logger = LogFactory.get();

    /**
     * 心跳丢失次数
     */
    private int counter = 0;

    protected void channelRead0(ChannelHandlerContext ctx, Response msg) throws Exception {
        // 收到消息直接打印输出
        logger.info("=====> 【下级平台|接收】指令 = {} ， 数据 = {}",Integer.toHexString(msg.getMsgId()), JSONUtil.toJsonStr(msg));

        // 开启线程执行业务方法
        ThreadUtil.execute(new ClientBusinessFactory(ctx, msg));
    }

    /**
     * 覆盖 channelActive 方法 在channel被启用的时候触发 (在建立连接的时候)
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // logger.info("==========> 【{}】 已连接 !", ctx.channel().remoteAddress());

        super.channelActive(ctx);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state().equals(IdleState.READER_IDLE)) {
                // 空闲40s之后触发 (心跳包丢失)
                if (counter >= 3) {
                    // 连续丢失3个心跳包 (断开连接)
                    ctx.channel().close().sync();
                    logger.info("已与" + ctx.channel().remoteAddress() + "断开连接");
                } else {
                    counter++;
                    logger.info(ctx.channel().remoteAddress() + "丢失了第 " + counter + " 个心跳包");
                }
            }

        }
    }
}
